package com.tg.app.activity.device.settings;

import static com.tg.app.activity.device.DeviceSettingsActivity.EXT_DEVICE_INFO;

import android.content.Intent;
import android.os.Bundle;
import android.view.Window;
import android.widget.ListView;

import androidx.core.util.Consumer;

import com.appbase.custom.base.SettingData;
import com.appbase.custom.constant.CommonConstants;
import com.appbase.custom.constant.DoubleLightModeConstants;
import com.tange.base.toolkit.TGThreadPool;
import com.tange.core.device.facade.ConnectStatus;
import com.tange.core.device.facade.DeviceFacade;
import com.tange.core.device.facade.Instruction;
import com.tange.core.device.facade.Status;
import com.tange.module.device.feature.DeviceFeature;
import com.tange.module.device.feature.DeviceFeatureObjectBox;
import com.tange.module.device.feature.DeviceFeature_;
import com.tg.app.R;
import com.tg.app.TGDevice;
import com.tg.app.activity.base.DeviceSettingsBaseActivity;
import com.tg.app.activity.device.DeviceSettingsActivity;
import com.tg.app.adapter.SettingAdapter;
import com.tg.app.camera.AVIOCTRLDEFs;
import com.tg.app.camera.CameraHelper;
import com.tg.app.helper.AppHelper;
import com.tg.app.helper.DeviceFeatureHelper;
import com.tg.appcommon.android.Packet;
import com.tg.appcommon.android.TGLog;
import com.tg.appcommon.android.TGToast;
import com.tg.data.bean.DeviceItem;
import com.tg.data.bean.DeviceSettingsInfo;

import java.util.ArrayList;

import io.objectbox.Box;

public class DoubleLightActivity extends DeviceSettingsBaseActivity {
    private static final String TAG = "DoubleLightActivity";
    private final ArrayList<SettingData> data = new ArrayList<>();
    private SettingAdapter adapter ;
    private DeviceFacade deviceFacade;
    private DeviceSettingsInfo info;

    private  int selectMode;
    private  int oldMode;
    private int clickPosition;
    private DeviceItem mDevice;

    private DeviceFeature deviceFeature;

    @Override
    protected void onSetupFailed() {
        setPositionByMode(oldMode);
    }

    private void setPositionByMode(int oldMode) {
        if (oldMode == DoubleLightModeConstants.DOUBLE_LIGHT_MODE_ON) {
            clickPosition = 1;
        } else if (oldMode == DoubleLightModeConstants.DOUBLE_LIGHT_MODE_AUTO) {
            clickPosition = 0;
        } else if (oldMode == DoubleLightModeConstants.DOUBLE_LIGHT_MODE_OFF) {
            clickPosition = 2;
        } else if (oldMode == DoubleLightModeConstants.DOUBLE_LIGHT_MODE_TIMER) {
            clickPosition = 3;
        }
        setFlag(clickPosition);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        requestWindowFeature(Window.FEATURE_NO_TITLE);//remove title bar  即隐藏标题栏
        hideActionBar();
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_double_light);


        Intent intent = getIntent();
        info  = intent.getParcelableExtra(DeviceSettingsActivity.EXT_DEVICE_INFO);
        mDevice = getIntent().getParcelableExtra(CommonConstants.EXT_DEVICE_ITEM);
        deviceFacade = new DeviceFacade(info.uuid);

        Box<DeviceFeature> featureBox = DeviceFeatureObjectBox.getDeviceFeature();
        deviceFeature = featureBox.query().equal(DeviceFeature_.uuid, info.uuid).build().findFirst();
        initView();
        registerICameraListener();

        initData();
        backClickEvent();
    }

    private void registerICameraListener(){
        if (deviceFacade != null) {
            deviceFacade.observeConnectStatus(connectStatusConsumer);
            deviceFacade.getInstruct().observeOnReceive(instructionConsumer);
        }
    }

    private void unregisterICameraListener(){
        if (deviceFacade != null) {
            deviceFacade.unObserveConnectStatus(connectStatusConsumer);
            deviceFacade.getInstruct().unObserveOnReceive(instructionConsumer);
        }
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterICameraListener();
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (deviceFacade !=null){
            deviceFacade.observeConnectStatus(connectStatusConsumer);
            if (!deviceFacade.connected()){
                deviceFacade.connect();
            }else {
                CameraHelper.getLightState(deviceFacade);
                CameraHelper.getCMDTimerTask(deviceFacade);
            }
        }
    }

    @Override
    public boolean shouldSetStatusBarColor() {
        return true;
    }

    @Override
    protected void initView() {
        adapter = new SettingAdapter(data,this);
        adapter.setCustomText(true);
        adapter.setItemTextSize(14.0f);
        adapter.setMarkTextSize(10.0f);

        ListView listView = findViewById(R.id.double_light_list);
        listView.setAdapter(adapter);
        listView.setOnItemClickListener((parent, view, position, id) -> {
            if (!TGDevice.getInstance().isNetwork(deviceFacade)){
                TGToast.showToast(R.string.txt_network_anomaly);
            }else{
                clickPosition = position;
                switch(position){
                    case 0:
                        setDoubleLight(DoubleLightModeConstants.DOUBLE_LIGHT_MODE_AUTO);//开
                        break;
                    case 1:
                        setDoubleLight(DoubleLightModeConstants.DOUBLE_LIGHT_MODE_ON);//标清
                        break;
                    case 2:
                        setDoubleLight(DoubleLightModeConstants.DOUBLE_LIGHT_MODE_OFF);//智能自动
                        break;
                    case 3:
                        setDoubleLight(DoubleLightModeConstants.DOUBLE_LIGHT_MODE_TIMER);
                        break;
                }
                setFlag(clickPosition);
            }
        });

        if (deviceFeature != null){
           setProgress();
        }
    }

    private void initData(){
        modifyToolBar(R.string.settings_light_mode);
        int type = info != null ? info.doubleLight : 0;
        SettingData enable = new SettingData(getString(R.string.open_alltime),0);
        SettingData disable = new SettingData(getString(R.string.always_off),0);
        SettingData auto = new SettingData(getString(R.string.auto),0);
        auto.setMark(getString(R.string.settings_double_light_auto_mark));
        data.add(auto);
        data.add(enable);
        data.add(disable);

        if (DeviceFeatureHelper.supportTimeAction(this.deviceFeature)){
            SettingData openRegularly = new SettingData(getString(R.string.settings_open_regularly), 0);
            data.add(openRegularly);
        }


        oldMode = type;
        selectMode = type;

        setPositionByMode(type);
    }

    private final Consumer<ConnectStatus> connectStatusConsumer = connectStatus -> {
        if (connectStatus.getStatus() == Status.SUCCESS){
            TGLog.d(TAG,"连接成功");
            CameraHelper.getLightState(deviceFacade);
            CameraHelper.getCMDTimerTask(deviceFacade);
        }else if (connectStatus.getStatus() == Status.FAILED){
            TGLog.d(TAG,"连接失败");
        }
    };

    private void setDoubleLight(int type){
        if (deviceFacade !=null){
            oldMode = selectMode;
            selectMode = type;
            AppHelper.sendIOCtrl(deviceFacade, AVIOCTRLDEFs.IOTYPE_USEREX_IPCAM_SET_DOUBLELIGHT_REQ,AVIOCTRLDEFs.SMsgAVIoctrlSetDoubleLightReq.parseContent(type));
        }
    }

    private void setFlag(int position){
        for(int i = 0; i< data.size(); i++){
            if(i == position){
                data.get(i).setFlag(1);
            }else{
                data.get(i).setFlag(0);
            }
        }

        adapter.notifyDataSetChanged();
    }

    @Override
    protected boolean onBackClick() {
        Intent intent = new Intent();
        intent.putExtra(EXT_DEVICE_INFO,info);
        setResult(RESULT_OK,intent);
        return super.onBackClick();
    }
    @Override
    protected void onPause() {
        super.onPause();
        if (deviceFacade !=null){
            deviceFacade.unObserveConnectStatus(connectStatusConsumer);
        }
    }
    private void setProgress(){
        TGThreadPool.executeOnUiThread(() -> {
            if (deviceFeature.lightIntensity < 1){
                deviceFeature.lightIntensity = 1;
            }
        });
    }


    private final Consumer<Instruction> instructionConsumer = new Consumer<Instruction>() {
        @Override
        public void accept(Instruction instruction) {
            if (instruction == null) {
                return;
            }
            final int type = instruction.getId();
            final byte[] data = instruction.getData();
            if (type == CameraHelper.TCI_CMD_GET_TIMER_TASK_RESP){
                int size = Packet.byteArrayToInt_Little(data, 4);
                TGLog.d(TAG, "DoubleLightActivity.receiveIOCtrlData.size = " + size);
                int p = 8;
                int count = 0;
                for (int i = 0; i < size; i++) {
                    int size1 = Packet.byteArrayToInt_Little(data, p);
                    short state = Packet.byteArrayToShort_Little(data, p + 12);
                    if (state == 1){
                        count++;
                    }
                    p += size1;
                }


            }else if (type==AVIOCTRLDEFs.IOTYPE_USEREX_IPCAM_SET_DOUBLELIGHT_RESP){
                runOnUiThread(() -> {
                    completeSend();
                    if (info == null) {
                        info = new DeviceSettingsInfo();
                    }
                    info.doubleLight  = selectMode;
                    sendUpdateSettingBroadcast(info);
                });
            } else if (type == AVIOCTRLDEFs.TCI_CMD_GET_LIGHT_RESP){
                CameraHelper.getLightData(data, deviceFeature);
                setProgress();
            }else if (type == AVIOCTRLDEFs.TCI_CMD_SET_COMMAND_RESP) {
                int command = Packet.byteArrayToInt_Little(data, 0);
                int result = Packet.byteArrayToInt_Little(data, 4);
                if (command == AVIOCTRLDEFs.TCI_CMD_SET_LIGHT_REQ){
                    if (result == 0){
                        if (deviceFeature != null){
                            Box<DeviceFeature> box = DeviceFeatureObjectBox.getDeviceFeature();
                            if (box != null) {
                                box.put(deviceFeature);
                            }
                        }
                    }
                }
            }
        }
    };

}